var setting = {
  async : {
    enable : true,
    url : "/warCategory/all",
    autoParam : [ "id=parentId" ],
    dataFilter : filter
  },
  view : {
    addHoverDom : addHoverDom,
    removeHoverDom : removeHoverDom,
    selectedMulti : false,
    nameIsHTML: true
  },
  edit: {
    drag: {
      autoExpandTrigger: true,
      isCopy: false,
      prev: dropPrev,
      inner: dropInner,
      next: dropNext
    },
    enable: true,
    showRemoveBtn: false,
    showRenameBtn: false
  },
  data : {
    simpleData : {
      enable : true
    }
  },
  callback : {
    beforeDrag : beforeDrag,
    onNodeCreated : function(event, treeId, treeNode) {
      // if(treeNode.id==1){
      var zTree = $.fn.zTree.getZTreeObj(treeId);
      zTree.reAsyncChildNodes(treeNode, "refresh", false);
      // }
    },
    onClick : onClick,
    beforeDrag: beforeDrag,
    beforeDrop: beforeDrop,
    beforeDragOpen: beforeDragOpen,
    onDrag: onDrag,
    onDrop: onDrop,
    onExpand: onExpand
  }
};
var log, className = "dark", curDragNodes, autoExpandNode;
var ctypes={1:'普通',2:'覆盖物',3:'内容层'}
var ctypecolors={1:'green',2:'blue',3:'red'}
canHidden = false;
function beforeDrag(treeId, treeNodes) {
  className = (className === "dark" ? "":"dark");
  for (var i=0,l=treeNodes.length; i<l; i++) {
    if (treeNodes[i].drag === false) {
      curDragNodes = null;
      return false;
    } else if (treeNodes[i].parentTId && treeNodes[i].getParentNode().childDrag === false) {
      curDragNodes = null;
      return false;
    }
  }
  curDragNodes = treeNodes;
  return true;
}
function beforeDragOpen(treeId, treeNode) {
  autoExpandNode = treeNode;
  return true;
}
function beforeDrop(treeId, treeNodes, targetNode, moveType, isCopy) {
  className = (className === "dark" ? "":"dark");
  if(isCopy )
    return false;
  var pid = moveType == 'inner' ? targetNode.id : targetNode.pId;
  //if(pid == treeNodes[0].pId) return false; 
  return true;
}
function onDrag(event, treeId, treeNodes) {
  className = (className === "dark" ? "":"dark");
}
function onDrop(event, treeId, treeNodes, targetNode, moveType, isCopy) {
  className = (className === "dark" ? "":"dark");
  if(moveType && moveType != null){//"inner"：成为子节点，"prev"：成为同级前一个节点，"next"：成为同级后一个节点
    $.ajax({
      async: false,
      url: "/warCategory/updateIdx2",
      data: {"cateId": treeNodes[0].id, "targetId": targetNode.id, "type": moveType},
      type: 'post',
      dataType: 'json',
      success: function(res){
        if(res.code==0){
          artDialog.tips("调整成功")
        }else{
          artDialog.alert(res.msg)
        }
      }
    });
  }
}
function onExpand(event, treeId, treeNode) {
  if (treeNode === autoExpandNode) {
    className = (className === "dark" ? "":"dark");
  }
}
function dropPrev(treeId, nodes, targetNode) {
  var pNode = targetNode.getParentNode();
  if (pNode && pNode.dropInner === false) {
    return false;
  } else {
    for (var i=0,l=curDragNodes.length; i<l; i++) {
      var curPNode = curDragNodes[i].getParentNode();
      if (curPNode && curPNode !== targetNode.getParentNode() && curPNode.childOuter === false) {
        return false;
      }
    }
  }
  if(targetNode.id == 0){
    return false;
  }
  return true;
}
function dropInner(treeId, nodes, targetNode) {
  if (targetNode && targetNode.dropInner === false) {
    return false;
  } else {
    for (var i=0,l=curDragNodes.length; i<l; i++) {
      if (!targetNode && curDragNodes[i].dropRoot === false) {
        return false;
      } else if (curDragNodes[i].parentTId && curDragNodes[i].getParentNode() !== targetNode && curDragNodes[i].getParentNode().childOuter === false) {
        return false;
      }
    }
  }
  return true;
}
function dropNext(treeId, nodes, targetNode) {
  var pNode = targetNode.getParentNode();
  if (pNode && pNode.dropInner === false) {
    return false;
  } else {
    for (var i=0,l=curDragNodes.length; i<l; i++) {
      var curPNode = curDragNodes[i].getParentNode();
      if (curPNode && curPNode !== targetNode.getParentNode() && curPNode.childOuter === false) {
        return false;
      }
    }
  }
  if(targetNode.id == 0){
    return false;
  }
  return true;
}
function filter(treeId, parentNode, childNodes) {
  if (childNodes.length == 0) {
    parentNode.isParent = false;
    return null;
  }
  var nodes = new Array();
  for (var i = 0, l = childNodes.length; i < l; i++) {
    var isParent = childNodes[i].childNum > 0;
    var qz = '';
    if(childNodes[i].type){
      qz = '[<span style="color:'+ctypecolors[childNodes[i].type]+'">'+ctypes[childNodes[i].type]+'</span>]';
    }
    nodes[i] = {
      'id' : childNodes[i].cateId,
      'pId' : childNodes[i].parentId,
      'name' : qz + childNodes[i].name,
      'cname' : childNodes[i].name,
      'isParent' : isParent,
      'open' : isParent,
      'overIcon': childNodes[i].overIcon,
      'enabled': childNodes[i].enabled,
      'type': childNodes[i].type,
    };
    if (childNodes[i].icon) {
      nodes[i]['icon'] = childNodes[i].icon;
    }
  }
  return nodes;
}
function onClick(event, treeId, treeNode, clickFlag) {
  if (!treeNode.isParent) {
    var html = "<span>[" + treeNode.cname + "]的图层数据</span><span class='btns'>";
    var icon = treeNode.overIcon ? treeNode.overIcon : (treeNode.icon ? treeNode.icon : "");
    var uri = encodeURI("/common/mgr/war/overData.html?cid="+treeNode.id+"&icon="+icon);
    if(treeNode.type == 1){
      html += "<input type='button' class='button green exportBtn' data-id='"+treeNode.id+"' data-template='1' style='height:18px;padding:0px 6px' value='导出图层["+treeNode.cname+"]模板'> " +
      "<input type='button' class='button green importBtn' data-id='"+treeNode.id+"' style='height:18px;padding:0px 6px' value='导入图层["+treeNode.cname+"]数据'> " +
      "<input type='button' class='button blue exportBtn' data-id='"+treeNode.id+"' style='height:18px;padding:0px 6px' value='导出图层["+treeNode.cname+"]数据'> " +
      "<input type='button' class='button red deleteBtn' data-id='"+treeNode.id+"' style='height:18px;padding:0px 6px' value='删除图层["+treeNode.cname+"]所有数据'> " +
      "<input type='button' class='button red tableBtn' data-id='"+treeNode.id+"' style='height:18px;padding:0px 6px' value='图层["+treeNode.cname+"]数据表格'> ";
    }else if(treeNode.type == 2){
      uri = encodeURI("/common/mgr/war/overPicData.html?cid="+treeNode.id);
    }else if(treeNode.type == 3){
      uri = encodeURI("/common/mgr/war/overTxtData.html?cid="+treeNode.id);
    }
    html += "</span>";
    $("#iframe").attr("src", uri).show();
    $(".frameTitle").html(html);
    canHidden = true;
    $(".deleteBtn").unbind().click(function(){
      var id = $(this).attr("data-id");
      var params={"cateId": id}
      artDialog.confirm("确定删除该图层所有数据？", function(){
        $.ajax({
          url : "/warInfo/delDatas/"+id,
          type : 'post',
          dataType : 'json',
          success : function(res) {
            if (res.code == 0) {
              $("#iframe")[0].contentWindow.document.location.reload();
              artDialog.alert("删除完成")
            } else {
              artDialog.alert(res.msg)
            }
          }
        });
      });
    });
    $(".exportBtn").unbind().click(function(){
      var id = $(this).attr("data-id");
      var template = $(this).attr("data-template");
      var params={"template": template, "cateId": id, "key": "warinfo", "handle": "com.star.truffle.module.fzjz.service.ExportWarInfo"}
      document.location.href="/download/excel/data?params="+encodeURI(JSON.stringify(params));
    });
    $(".importBtn").unbind().click(function(){
      var id = $(this).attr("data-id");
      artDialog.data("params", {"importHandle": "com.star.truffle.module.fzjz.service.ImportWarInfo", "cateId": id});
      artDialog.open("common/upload/excels", {
        title : "导入图层数据",
        width : "90%",
        height : "90%",
        drag : true,
        resize : true,
        lock : true, 
        close:function(){$("#iframe")[0].contentWindow.document.location.reload();}
      });
    });
    $(".tableBtn").unbind().click(function(){
      var id = $(this).attr("data-id");
      artDialog.data("params", {"viewMarker": function(id){
        $("#iframe")[0].contentWindow.starMap.viewMarker({"id": id});
      }});
      artDialog.open("/warInfo/lists/"+id, {
        title : "图层数据",
        width : "90%",
        height : "90%",
        drag : true,
        resize : true,
        lock : true
      });
    });
  } else {
    if (canHidden) {
      $(".frameTitle").text("");
      $("#iframe").attr("src", "about:blank").hide();
    }
  }
}

var newCount = 1;
function addHoverDom(treeId, treeNode) {
  var sObj = $("#" + treeNode.tId + "_span");
  if (treeNode.editNameFlag || $("#editBtn_" + treeNode.tId).length > 0 || $("#addBtn_" + treeNode.tId).length > 0)
    return;
  var addStr = "";
  if (treeNode.level <= 1) {
    addStr += "<span class='button add' id='addBtn_" + treeNode.tId + "' title='新增菜单' onfocus='this.blur();'></span>";
  }
  if (treeNode.id > 0) {
    addStr += '<span class="button edit" id="editBtn_' + treeNode.tId + '" title="编辑菜单" onfocus="this.blur();"></span>';
  }
  if (treeNode.level == 2) {
    if(treeNode.enabled == 1){
      addStr += '<span class="button star_open" id="viewCloseBtn_' + treeNode.tId + '" title="图层已显示" onfocus="this.blur();"></span>';
    }else{
      addStr += '<span class="button star_close" id="viewOpenBtn_' + treeNode.tId + '" title="图层已隐藏" onfocus="this.blur();"></span>';
    }
  }
  if (!treeNode.isParent) {
    addStr += '<span class="button remove" id="removeBtn_' + treeNode.tId + '" title="删除菜单" onfocus="this.blur();"></span>';
  }
  if (treeNode.id > 0) {
    addStr += '<span class="up" id="upBtn_' + treeNode.tId + '" title="上移" onfocus="this.blur();"></span>';
    addStr += '<span class="down" id="downBtn_' + treeNode.tId + '" title="下移" onfocus="this.blur();"></span>';
  }
  sObj.after(addStr);
  var btn = $("#upBtn_" + treeNode.tId);
  if (btn)
    btn.bind("click", function() {
      $.ajax({
        url : "/warCategory/updateIdx",
        data: {"cateId": treeNode.id, "brotherId": treeNode.getPreNode().id, "type": "up"},
        type : 'post',
        dataType : 'json',
        success : function(res) {
          if (res.code == 0) {
            artDialog.tips("操作成功");
            var zTree = $.fn.zTree.getZTreeObj(treeId);
            zTree.moveNode(treeNode.getPreNode(), treeNode, "prev", true);
          } else {
            artDialog.alert(res.msg)
          }
        }
      });
      return false;
    });
  var btn = $("#downBtn_" + treeNode.tId);
  if (btn)
    btn.bind("click", function() {
      $.ajax({
        url : "/warCategory/updateIdx",
        data: {"cateId": treeNode.id, "brotherId": treeNode.getNextNode().id, "type": "up"},
        type : 'post',
        dataType : 'json',
        success : function(res) {
          if (res.code == 0) {
            artDialog.tips("操作成功");
            var zTree = $.fn.zTree.getZTreeObj(treeId);
            zTree.moveNode(treeNode.getNextNode(), treeNode, "next", true);
          } else {
            artDialog.alert(res.msg)
          }
        }
      });
      return false;
    });
  var btn = $("#viewCloseBtn_" + treeNode.tId);
  if (btn)
    btn.bind("click", function() {
      artDialog.confirm("确定隐藏该图层所有数据？<br>图层隐藏后，图层数据在前端将不可见", function(){
        $.ajax({
          url : "/warCategory/disabled",
          data: {"ids": treeNode.id},
          type : 'post',
          dataType : 'json',
          success : function(res) {
            if (res.code == 0) {
              artDialog.tips("操作成功");
              treeNode.enabled = 0;
              btn.removeClass("star_open").addClass("star_close");
            } else {
              artDialog.alert(res.msg)
            }
          }
        });
      });
      return false;
    });
  var btn = $("#viewOpenBtn_" + treeNode.tId);
  if (btn)
    btn.bind("click", function() {
      artDialog.confirm("确定显示该图层所有数据？<br>图层显示后，图层数据在前端将可见", function(){
        $.ajax({
          url : "/warCategory/enabled",
          data: {"ids": treeNode.id},
          type : 'post',
          dataType : 'json',
          success : function(res) {
            if (res.code == 0) {
              artDialog.tips("操作成功");
              treeNode.enabled = 1;
              btn.addClass("star_open").removeClass("star_close");
            } else {
              artDialog.alert(res.msg)
            }
          }
        });
      });
      return false;
    });
  var btn = $("#addBtn_" + treeNode.tId);
  if (btn)
    btn.bind("click", function() {
      var zTree = $.fn.zTree.getZTreeObj(treeId);
      artDialog.data("params", {
        'parentNode' : treeNode,
        'zTree' : zTree
      });
      artDialog.open("/common/mgr/warCategory/addWarCategory", {
        title : "新增[" + treeNode.cname + "]下的" + (treeNode.id == 0 ? "分类" : "图层"),
        width : "80%",
        height : treeNode.id == 0 ? "200px" : "600px",
        drag : true,
        resize : false,
        lock : true
      });
      return false;
    });
  var editBtn = $("#editBtn_" + treeNode.tId);
  if (editBtn)
    editBtn.bind("click", function() {
      var zTree = $.fn.zTree.getZTreeObj(treeId);
      artDialog.data("params", {
        'parentNode' : treeNode.getParentNode(),
        'zTree' : zTree
      });
      artDialog.open("/warCategory/editBefore/" + treeNode.id, {
        title : "编辑" + (treeNode.pId == 0 ? "分类" : "图层") + "[" + treeNode.cname + "]",
        width : "80%",
        height : treeNode.pId == 0 ? "200px" : "600px",
        drag : true,
        resize : false,
        lock : true
      });
      return false;
    });
  var removeBtn = $("#removeBtn_" + treeNode.tId);
  if (removeBtn)
    removeBtn.bind("click", function() {
      var zTree = $.fn.zTree.getZTreeObj(treeId);
      artDialog.confirm("确认删除" + (treeNode.id == 0 ? "分类" : "图层") + "[" + treeNode.cname + "]？", function() {
        $.ajax({
          url : "/warCategory/deleted",
          data: {"ids": treeNode.id},
          type : 'post',
          dataType : 'json',
          success : function(res) {
            if (res.code == 0) {
              zTree.removeNode(treeNode);
            } else {
              artDialog.alert(res.msg)
            }
          }
        });
      });
      return false;
    });
};
function removeHoverDom(treeId, treeNode) {
  $("#addBtn_" + treeNode.tId).unbind().remove();
  $("#editBtn_" + treeNode.tId).unbind().remove();
  $("#viewOpenBtn_" + treeNode.tId).unbind().remove();
  $("#viewCloseBtn_" + treeNode.tId).unbind().remove();
  $("#removeBtn_" + treeNode.tId).unbind().remove();
  $("#upBtn_" + treeNode.tId).unbind().remove();
  $("#downBtn_" + treeNode.tId).unbind().remove();
};

$(document).ready(function() {
  var screenHeight = document.documentElement.clientHeight || document.body.clientHeight;
  $.fn.zTree.init($("#resourceTree"), setting);
  $("ul.ztree").css("height", (screenHeight - 20) + "px");
  $("#iframe").height(screenHeight - 35);
});